<template>
  <div class="w1 h1"
    ref="chart-dom">
  </div>
</template>
<script>
import { getIndexTop3 } from '@/api'
let resize = null
export default {
  props: {
    companyId: {
      type: String,
      default: ''
    }
  },
  watch: {
    companyId() {
      this.init()
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      const vm = this
      const companyId = vm.companyId
      if (!companyId) {
        return
      }
      const params = { companyId }
      const { code, data } = await getIndexTop3(params)
      if (code != 200) {
        return
      }
      vm.$nextTick(() => {
        const dom = this.$refs['chart-dom']
        const echartsInstence = vm.echarts.init(dom)
        echartsInstence.showLoading({
          text: '',
          color: 'red'
        })
        if (data.length === 0) {
          echartsInstence.clear()
          echartsInstence.setOption({
            title: {
              text: '暂无数据',
              textStyle: {
                color: '#fff',
                fontWeight: 'bold',
                fontSize: 28
              },
              left: 'center',
              top: 'center'
            }
          })
          echartsInstence.hideLoading()
        } else {
          const title = []
          const series = data.map(t => {
            t['name'] = t.deviceName
            title.push[t.deviceName]
            delete t.deviceName
            return t
          })
          const option = {
            tooltip: {
              trigger: 'item',
              formatter: '{b}<br/> 总有功功率: {c}kW'
            },
            color: ['#1890FF', '#2FC25B', '#FACC14'],
            legend: { show: false },
            series: [
              {
                name: '实时功率TOP3',
                type: 'pie',
                center: ['45%', '45%'],
                radius: ['40%', '60%'],
                avoidLabelOverlap: true,
                labelLine: {
                  normal: {
                    show: true
                  }
                },
                data: series
              }
            ]
          }
          echartsInstence.setOption(option)
          echartsInstence.hideLoading()
          resize = () => echartsInstence.resize()
          window.addEventListener('resize', resize)
        }
      })
    }
  },
  beforeDestroy() {
    if (resize) {
      window.removeEventListener('resize', resize)
    }
  }
}
</script>
